package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.demo.dto.*;
import com.example.demo.entity.SysUser;
import com.example.demo.mapper.SysUserMapper;
import com.example.demo.model.PageBean;
import com.example.demo.model.Result;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.PasswordEncoder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@AllArgsConstructor
public class SysUserService {

    private SysUserMapper sysUserMapper;
    private JwtUtils jwtUtils;
    private PasswordEncoder passwordEncode;

    public Result login(LoginDto loginDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", loginDto.getUsername());
        queryWrapper.eq("status", 1);

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        if(null == sysUser || !passwordEncode.matches(loginDto.getPassword(), sysUser.getPassword())) {
            return Result.buildFail("用户名或密码错误");
        }else {
            // 构建jwt
            Object jwt = jwtUtils.createAccessToken(sysUser.getName());
            // 往前端返回jwt字符串
            return Result.buildSuccess(jwt);
        }
    }

    public Result getPageData(QuerySysUserDto querySysUserDto, PaginationDto paginationDto) {
        PageBean<SysUser> pageBean = new PageBean<>();
        Map<String, Object> params = new HashMap<>();

        // 因为是 like 查询所以要拼接 %
        if(StringUtils.hasText(querySysUserDto.getName())) {
            params.put("name", "%" + querySysUserDto.getName() + "%");
        }

        if(StringUtils.hasText(querySysUserDto.getMobile())) {
            params.put("mobile", "%" + querySysUserDto.getMobile() + "%");
        }

        if(StringUtils.hasText(querySysUserDto.getEmail())) {
            params.put("email", "%" + querySysUserDto.getEmail() + "%");
        }

        // 为什么要下查询总数? 因为要做分页合理化考虑
        Long total = sysUserMapper.getTotal(params);

        // 计算得到总的页数, 19 -> 2   20 -> 2   21 -> 3
        long totalPages = (total + paginationDto.getSize() - 1) / paginationDto.getSize(); // 计算得到总页数

        // 如果总的页数为0， 后面的逻辑没必要走了
        if(totalPages == 0) {
            pageBean.setTotal(0L);
            return Result.buildSuccess(pageBean);
        }
        // 如果当前页大于总页数，那么就取最大页为最后一页
        if(paginationDto.getCurrent() > totalPages) {
            // limit 0, 10  limit 10 10   limit 20 10
            params.put("idx", (totalPages - 1) * paginationDto.getSize());
            paginationDto.setCurrent(totalPages);
        }else if(paginationDto.getCurrent() <= 0) {
            params.put("idx", 0);
            paginationDto.setCurrent(1);  // 设置当前页为1
        }else {
            params.put("idx", (paginationDto.getCurrent() - 1) * paginationDto.getSize());
        }

        params.put("size", paginationDto.getSize());

        List<SysUser> sysUsers = sysUserMapper.getPageData(params);


        pageBean.setTotal(total);
        pageBean.setData(sysUsers);
        pageBean.setCurrent(paginationDto.getCurrent());

        return Result.buildSuccess(pageBean);
    }

    /**
     * update sys_user set status = 1 where id = 23 and status = 0
     * @param statusDto
     * @return
     */
    public Result changeStatus(StatusDto statusDto) {
        sysUserMapper.updateStatus(statusDto);
        return Result.buildSuccess();
    }

    public Result getById(Integer id) {
        return Result.buildSuccess(sysUserMapper.getById(id));
    }

    public Result addSysUser(SysUserDto sysUserDto) {
        sysUserMapper.addSysUser(sysUserDto);
        sysUserMapper.addUserRole(sysUserDto);
        return Result.buildSuccess();
    }

    public Result getByIdForEdit(Integer id) {
        return Result.buildSuccess(sysUserMapper.getByIdForEdit(id));
    }

    public Result edit(SysUserDto sysUserDto) {
        // 更新用户表
        sysUserMapper.editSysUser(sysUserDto);
        // 删除用户原有的角色信息
        sysUserMapper.deleteUserRole(sysUserDto.getId());
        // 添加新的角色
        sysUserMapper.addUserRole(sysUserDto);

        return Result.buildSuccess();
    }

    public Boolean delById(Integer id){
        //删除sys-user中的数据
        return (sysUserMapper.deleteById(id)>0) && (sysUserMapper.deleteUserRole(id)>0);
    }
}
